package controller;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

@Controller
public class DownloadController {

    @RequestMapping("/download1")
    public void download1(HttpServletResponse response, HttpSession session) throws UnsupportedEncodingException {
        response.setHeader("content-disposition",new String("attachment;filename=spring啊.zip".getBytes("utf-8"),"iso8859-1"));

        ServletContext application=session.getServletContext();

//        String realPath=application.getRealPath("file/spring.zip");
//
//        System.out.println(realPath);

        Resource resource=new ClassPathResource("file/spring.zip");

//        System.out.println(resource.exists());

        InputStream in=null;
        OutputStream out=null;
        try {
            in=resource.getInputStream();
            out=response.getOutputStream();



            byte[] b=new byte[2048];

            int n;

            while((n=in.read(b))!=-1){
                out.write(b,0,n);
            }




        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if (in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



    }



    @RequestMapping("/download2")
    public ResponseEntity<byte[]> download2()throws Exception{
        HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment","spring.zip");


        Resource resource=new ClassPathResource("file/spring.zip");


        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(resource.getFile()),
                                          headers,
                                          HttpStatus.OK);
    }
















}
